from PySide6.QtWidgets import QWidget,QAbstractItemView,QMenu,QTableWidgetItem,QMessageBox
from PySide6.QtCore import Qt
from sqlalchemy.orm import Session
from settings.publicvar import engine
from settings.publicFuncation.exceldownloadimport import OperationModel
from views.bankinfo.model.bankinfo import BankCard
from views.bankinfo.bankcard.bankcard import Ui_bankcard
from views.bankinfo.bankcard.operationbankcardView import OperationBankCardView

class BankCardView(QWidget,Ui_bankcard):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.bankcardtable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.bankcardtable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.bankcardtable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.bankcardtable.customContextMenuRequested.connect(self.generate_menu)

        self.loadTableData()
        self.addbtn.clicked.connect(self.addFun)
        self.sereachedit.editingFinished.connect(self.serearchFun)
        self.serearchbtn.clicked.connect(self.serearchFun)
        self.downloadmodle.clicked.connect(self.downloadmodleFun)
        self.importbtn.clicked.connect(self.importdataFun)


        # 读取所有数据
    def loadTableData(self):
        with Session(engine) as session, session.begin():
            personothers = session.query(BankCard).all()
            self.setTableStructure(personothers)

    # 表格加载数据
    def setTableStructure(self, data):
        self.bankcardtable.setRowCount(len(data))
        for i, item in enumerate(data):
            idx = QTableWidgetItem(str(item.id))
            self.bankcardtable.setItem(i, 0, idx)
            bankname = QTableWidgetItem(item.bankname)
            self.bankcardtable.setItem(i, 1, bankname)
            name = QTableWidgetItem(item.name)
            self.bankcardtable.setItem(i, 2, name)
            IDNumber = QTableWidgetItem(item.IDNumber)
            self.bankcardtable.setItem(i, 3, IDNumber)
            cardnumber = QTableWidgetItem(item.cardnumber)
            self.bankcardtable.setItem(i, 4, cardnumber)
            openbank = QTableWidgetItem(item.openbank)
            self.bankcardtable.setItem(i, 5, openbank)
            IDtype = QTableWidgetItem(item.IDtype)
            self.bankcardtable.setItem(i, 6, IDtype)
            mark = QTableWidgetItem(item.mark)
            self.bankcardtable.setItem(i, 7, mark)


    def addFun(self):
        add = OperationBankCardView('add',False)
        add.exec()
        self.loadTableData()

    # 获取表单
    def generate_menu(self,pos):
        menu = QMenu()
        viewitem = menu.addAction('查看')
        changeitem = menu.addAction('修改')
        deleteitm = menu.addAction('删除')
        action = menu.exec(self.bankcardtable.mapToGlobal(pos))
        posrow = self.bankcardtable.currentRow()
        columns = self.bankcardtable.columnCount()
        data = [self.bankcardtable.item(posrow, i).text() for i in range(columns)]
        for i in range(columns):
            item = self.bankcardtable.item(posrow,i)
            if item is None:
                data.append('')
            else:
                data.append(item.text())
        if action == viewitem:
            view = OperationBankCardView('view', data)
            view.exec()
        elif action == changeitem:
            change = OperationBankCardView('change', data)
            change.exec()
        elif action == deleteitm:
            delete = OperationBankCardView('delete',data)
            delete.exec()
        self.loadTableData()

    # 搜索框数据处理
    def serearchFun(self):
        sereachdata = self.sereachedit.text().strip()
        if sereachdata == '':
            QMessageBox.critical(None, '错误', '搜索框不能为空！')
            self.loadTableData()
        else:
            with Session(engine) as session, session.begin():
                sereachbankname = session.query(BankCard).filter(
                    BankCard.bankname.like('%' + sereachdata + '%')).all()
                sereachname = session.query(BankCard).filter(
                    BankCard.name.like('%' + sereachdata + '%')).all()
                sereachIDNumber = session.query(BankCard).filter(
                    BankCard.IDNumber.like('%' + sereachdata + '%')).all()
                sereachcardnumber = session.query(BankCard).filter(
                    BankCard.cardnumber.like('%' + sereachdata + '%')).all()
                sereachopenbank = session.query(BankCard).filter(
                    BankCard.openbank.like('%' + sereachdata + '%')).all()
                sereachIDtype = session.query(BankCard).filter(
                    BankCard.IDtype.like('%' + sereachdata + '%')).all()
                sereachData = sereachbankname + sereachname + sereachIDNumber+sereachcardnumber+sereachopenbank+sereachIDtype
                items = []
                if sereachData:
                    for item in sereachData:
                        items.append(item)
                else:
                    QMessageBox.critical(None,'没有数据','你搜索数据不存在！')
                self.setTableStructure(items)

    def downloadmodleFun(self):
        OperationModel().downloadmodleFun('银行卡信息模板.xlsx')

    def importdataFun(self):
        items_names = ['idx','bankname','name','IDNumber','cardnumber','openbank','IDtype','mark']
        dtypes = {'IDNumber': str,'cardnumber':str}
        data = OperationModel().importdataFun(items_names,dtypes)
        with Session(engine) as session,session.begin():
            exit_card = session.query(BankCard).filter(BankCard.cardnumber.in_(data.cardnumber.to_list())).all()
            not_exit_card = [item.cardnumber for item in exit_card]
            save_card = data[~data.cardnumber.isin(not_exit_card)].to_dict('records')
            items = [BankCard(**item) for item in save_card]
            session.add_all(items)
            QMessageBox.information(None, '提示', '你导入成功%s条，失败%s条，明细如下！' % (len(items), len(data) - len(items)))
        self.loadTableData()